﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using University.Workshop.Presenters.CollectControl;
using System.Collections;
using System.Windows.Controls.Primitives;

namespace University.Workshop.Presentation.CollectControl
{
    public partial class RegisterPayment : Page, IRegisterCollectControlView
    {
        PresenterRegisterCollectControl pRegisterCollectControl;
        List<Model.CollectControl> seleccionados = new List<Model.CollectControl>();
        Dictionary<string, ICollection<Model.Allotment>> manzanos;
        bool buscar;
        decimal totalSeleccionado = 0;
        //decimal totalDescuento = 0;
        //int descuento = 1;
        bool existeCorte;

        Model.User user;

        public RegisterPayment(Model.User user)
        {
            pRegisterCollectControl = new PresenterRegisterCollectControl(this, user);
            manzanos = new Dictionary<string, ICollection<Model.Allotment>>();
            this.user = user;
            
            InitializeComponent();
            LlenarCbx();
            existeCorte = false;
        }

        public void LlenarCbx()
        {
            manzanos = pRegisterCollectControl.LlenarCbx();

            foreach (KeyValuePair<string, ICollection<Model.Allotment>> kv in manzanos)
            {
                ManzanoCbx.Items.Add(kv.Key);
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            App.Current.MainWindow.Title = "Realizar Cobro";
        }

        private void CantCupyPasteOrCut(object sender, CanExecuteRoutedEventArgs e)
        {
            if (e.Command == ApplicationCommands.Copy)
                e.Handled = true;
            if (e.Command == ApplicationCommands.Cut)
                e.Handled = true;
            if (e.Command == ApplicationCommands.Paste)
                e.Handled = true;
        }

        private void ClientIdTxt_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                e.Handled = true;
            }
        }

        private void ClientIdTxt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            string temporal = ((TextBox)sender).Text + e.Text;
            foreach (char ch in e.Text)
            {
                e.Handled = !(char.IsDigit(ch));
            }
        }

        /*private void SearchBtn_Click(object sender, RoutedEventArgs e)
        {
            bool encontro;

            encontro = pRegisterCollectControl.SearchCollects();
            if (encontro)
                RealizarBtn.Visibility = Visibility.Visible;
            else
                RealizarBtn.Visibility = Visibility.Hidden;
        }*/

        private void RealizarBtn_Click(object sender, RoutedEventArgs e)
        {
            bool seProceso = false;

            seProceso = pRegisterCollectControl.PayCollects(seleccionados);
            if (seProceso)
            {
                MessageBox.Show("El pago fue registrado exitosamente.");
                this.NavigationService.Navigate(new RegisterPayment(user));
            }
            //else
            //    MessageBox.Show("Hola man");
        }

        #region IRegisterCollectControlView Members

        public string Manzano
        {
            get 
            {
                return ManzanoCbx.SelectedValue.ToString();
            }
        }

        public string Lote
        {
            get 
            {
                return LoteCbx.SelectedValue.ToString();
            }
        }

        //public int Descuento
        //{
        //    get
        //    {
        //        switch(DescuentoCbx.SelectedIndex)
        //        {
        //            case 0: return 0;
        //            case 1: return 10;
        //            case 2: return 15;
        //            case 3: return 20;
        //            case 4: return 25;
        //            case 5: return 30;
        //        }
        //        return 0;
        //    }
        //}

        public string NombreSocio
        {
            set 
            {
                if (value != String.Empty)
                    SocioLbl.Content = value;
                else
                    SocioLbl.Content = "-";
            }
        }

        public string CiSocio
        {
            set 
            {
                if (value != String.Empty)
                    CiLbl.Content = value;
                else
                    CiLbl.Content = "-";
            }
        }

        public decimal TotalAmount
        {
            set
            {
                if (value != 0)
                    TotalAmountLbl.Content = value;
                else
                    TotalAmountLbl.Content = "-";

            }
        }

        public ICollection<Model.CollectControl> CollectFinded
        {
            get
            {
                if (ChargeFindedDgv.ItemsSource == null)
                    new List<Model.CollectControl>();
                return (ICollection<Model.CollectControl>)ChargeFindedDgv.ItemsSource;
            }
            set
            {
                ChargeFindedDgv.ItemsSource = null;
                ChargeFindedDgv.ItemsSource = value;
            }
        }

        public ICollection<Model.CollectControl> CollectsSelected
        {
            get
            {
                int cantidad = ChargeFindedDgv.SelectedItems.Count;
                List<Model.CollectControl> charges = new List<Model.CollectControl>();

                for (int i = 0; i < cantidad; i++)
                    charges.Add((Model.CollectControl)ChargeFindedDgv.SelectedItems[i]);

                return charges;
            }
        }

        public void NotifyErrorMessage(string MessageValue)
        {
            MessageBox.Show(App.Current.MainWindow, MessageValue, "Error!!!", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, MessageBoxOptions.RightAlign);
        }

        public bool NotifyConfirmationMessage(string MessageValue)
        {
            return MessageBox.Show(App.Current.MainWindow,
                MessageValue,
                "Atención!!!",
                MessageBoxButton.YesNo,
                MessageBoxImage.Information,
                MessageBoxResult.Yes,
                MessageBoxOptions.RightAlign) == MessageBoxResult.Yes;
        }

        #endregion

        public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
        {
            var itemsSource = grid.ItemsSource as IEnumerable;
            if (null == itemsSource) yield return null;
            foreach (var item in itemsSource)
            {
                var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (null != row) yield return row;
            }
        }

        public DataGridRow GetRow(int index)
        {
            DataGridRow row = (DataGridRow)ChargeFindedDgv.ItemContainerGenerator.ContainerFromIndex(index);
            if (row == null)
            {
                ChargeFindedDgv.UpdateLayout();
                ChargeFindedDgv.ScrollIntoView(ChargeFindedDgv.Items[index]);
                row = (DataGridRow)ChargeFindedDgv.ItemContainerGenerator.ContainerFromIndex(index);
            }
            return row;
        }

        public static T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = v as T;
                if (child == null)
                {
                    child = GetVisualChild<T>
                    (v);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        } 

        public DataGridCell GetCell(int row, int column)
        {
            DataGridRow rowContainer = GetRow(row);
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                if (presenter == null)
                {
                    ChargeFindedDgv.ScrollIntoView(rowContainer, ChargeFindedDgv.Columns[column]);
                    presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                }
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                return cell;
            }
            return null;
        } 

        private void Seleccionados_Click(object sender, RoutedEventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            Model.CollectControl collect = (Model.CollectControl)ChargeFindedDgv.SelectedItem;

            int indexActual=0;

            var row_list = GetDataGridRows(ChargeFindedDgv);
            foreach (DataGridRow single_row in row_list)
            {
                if (single_row.IsSelected == true)
                {
                    indexActual = single_row.GetIndex();
                    break;
                }
            }

            if (cb.IsChecked.Value)
            {
                seleccionados.Add(collect);
                totalSeleccionado += collect.PaymentAmount;

                for (int j = 0; j < indexActual; j++)
                {
                    DataGridCell cell = GetCell(j, 3);
                    CheckBox chk = GetVisualChild<CheckBox>(cell);
                    chk.IsChecked = true;

                    collect = (Model.CollectControl)ChargeFindedDgv.Items[j];
                    if (!seleccionados.Contains(collect))
                    {
                        seleccionados.Add(collect);
                        totalSeleccionado += collect.PaymentAmount;
                    }
                }

            }
            else
            {
                totalSeleccionado -= collect.PaymentAmount;
                seleccionados.Remove(collect);
            }

            //if (Descuento != 0)
            //{
            //    double cantidadDescuento = Descuento / 100;
            //    double aDescontar = (double)totalSeleccionado * cantidadDescuento;
                
            //    AmountPayLbl.Content = ((double)totalSeleccionado - aDescontar).ToString();
            //}
            //else
            //    AmountPayLbl.Content = totalSeleccionado.ToString();


            AmountPayLbl.Content = totalSeleccionado.ToString();
        }

        private void ManzanoCbx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CleanSearch();

            if (!LoteCbx.IsEnabled)
                LoteCbx.IsEnabled = true;
            else
            {
                if (LoteCbx.HasItems)
                    buscar = false;
                LoteCbx.Items.Clear();
            }

            ICollection<Model.Allotment> lotes = manzanos[ManzanoCbx.SelectedItem.ToString()];

            foreach (Model.Allotment a in lotes)
                LoteCbx.Items.Add(a.AllotmentName);

            buscar = true;
        }

        private void LoteCbx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            bool encontro = false;
            CleanSearch();

            if (buscar)
                encontro = pRegisterCollectControl.SearchCollects();

            if (encontro)
            {
                existeCorte = pRegisterCollectControl.VerificarCorte();
                if (existeCorte)
                {
                    SeleccionarCheckBoxes();
                    lblCorte.Visibility = Visibility.Visible;
                }

                RealizarBtn.IsEnabled = true;
                //DescuentoCbx.IsEnabled = true;
            }
            else
            {
                RealizarBtn.IsEnabled = false;
                //DescuentoCbx.IsEnabled = false;

                existeCorte = false;
                lblCorte.Visibility = Visibility.Hidden;
            }
        }

        private void SeleccionarCheckBoxes()
        {
            var row_list = GetDataGridRows(ChargeFindedDgv);
            Model.CollectControl collect;

            int cantidadCobros = ChargeFindedDgv.Items.Count;

            if (cantidadCobros > 0)
            {
                for (int i = 0; i < cantidadCobros; i++)
                {
                    collect = (Model.CollectControl)ChargeFindedDgv.Items[i];

                    seleccionados.Add(collect);
                    totalSeleccionado += collect.PaymentAmount;

                    DataGridCell cell = GetCell(i, 3);
                    CheckBox chk = GetVisualChild<CheckBox>(cell);
                    chk.IsChecked = true;
                    chk.IsHitTestVisible = false;
                }

                //if (Descuento != 0)
                //{
                //    decimal cantidadDescuento = Descuento / 100;
                //    decimal aDescontar = totalSeleccionado * cantidadDescuento;
                //    AmountPayLbl.Content = (totalSeleccionado-aDescontar).ToString();
                //}
                //else
                
                AmountPayLbl.Content = totalSeleccionado.ToString();
            }
        }

        private void CleanSearch()
        {
            NombreSocio = string.Empty;
            CiSocio = string.Empty;
            totalSeleccionado = 0;

            TotalAmountLbl.Content = "-";
            AmountPayLbl.Content = "-";
            seleccionados = new List<Model.CollectControl>();
            ChargeFindedDgv.ItemsSource = null;

            existeCorte = false;
            lblCorte.Visibility = Visibility.Hidden;
        }
    }
}
